import * as types from '@/store/mutation-types.js';
import api from "@/api/common";
import { sha256 } from "js-sha256"
import { setStore, getStore } from "@/common/util"


export default {
    namespaced: true,
    state: {
        userInfo: getStore('userInfo') ? JSON.parse(getStore('userInfo')) : null,
        authorityList: getStore('authorityList') ? JSON.parse(getStore('authorityList')) : null,
    },
    getters: {
        getUserInfo: (state) => {
            const { userInfo } = state;
            return userInfo;
        },
    },
    actions: {
        // 用户类型 1：管理员 2：坊主 3：学员
        async login ({ commit, dispatch }, form) {
            try {
                let params = { ...form }
                console.log(sha256);
                params.password = sha256(params.password)
                console.log(params.password)
                const res = await api.login(params)
                if (res) {
                    commit(types.SET_USER_INFO, res.result);
                    //管理端获取权限
                    await dispatch('getJurisdiction')
                    return Promise.resolve(true)
                }
            } catch (e) {
                console.log(e)
            }
        },
        //获取权限
        async getJurisdiction ({ commit, state },) {
            const { result } = await api.getJurisdiction({ roles: state.userInfo.roles });
            if (result) {
                commit(types.AUTHORITY_LIST, result);
            }
        }
    },
    mutations: {
        [types.SET_USER_INFO] (state, userInfo) {
            setStore('userInfo', userInfo)
            state.userInfo = userInfo;
        },
        [types.AUTHORITY_LIST] (state, result) {
            setStore('authorityList', result)
            state.authorityList = result;
            console.log(result);
        },
    },
};
